import shallow from 'zustand/shallow'
import { useVirtualRoomStore } from '../../../store'
import { CheckBox, InputNumber, Select } from '@kedacom/react-next'
import { useEffect, useMemo, useRef, useState } from 'react'
import { getRule } from '../../../rules'
import { t } from 'i18next'
import { useDebounceFn } from 'ahooks'
import {
	setMediaAbilityVal,
	setSelfMediaAbilityList,
	setSelfMediaAbilityVal,
	setSfuMediaValue,
} from '../../../store.media'

export default function MedialAbility({ containerRef }: { containerRef: React.MutableRefObject<null> }) {
	const [value, setValue] = useState('')
	const inputRef = useRef<HTMLDivElement | null>(null)
	const { data, permission, updateData, resetMeetingProtocol, changeH265 } = useVirtualRoomStore(
		(state) => ({
			data: state.data,
			permission: state.permission,
			updateData: state.updateData,
			changeH265: state.changeH265,
			resetMeetingProtocol: state.resetMeetingProtocol,
		}),
		shallow
	)

	const mediaAbilityList = useMemo(() => {
		//媒体能力下拉列表
		let supportedFps = []
		if (!permission['60fps']) {
			supportedFps = [
				{
					value: 4,
					label: t('全高清（2M 1080P@30fps）'),
				},
				{
					value: 3,
					label: t('高清（2M 720P@30fps）'),
				},
				{
					value: 2,
					label: t('标清（256K W4CIF@25fps）'),
				},
				{
					value: 1,
					label: t('流畅（192K WCIF@25fps）'),
				},
				{
					value: 0,
					label: t('自定义'),
				},
			]
		} else {
			if (data._H265) {
				supportedFps = [
					{
						value: 7,
						label: t('超高清（8M 4K@60fps）'),
					},
					{
						value: 6,
						label: t('超高清（4M 4K@30fps）'),
					},
					{
						value: 5,
						label: t('全高清（4M 1080P@60fps）'),
					},
					{
						value: 4,
						label: t('全高清（2M 1080P@30fps）'),
					},
					{
						value: 3,
						label: t('高清（2M 720P@30fps）'),
					},
					{
						value: 2,
						label: t('标清（256K W4CIF@25fps）'),
					},
					{
						value: 1,
						label: t('流畅（192K WCIF@25fps）'),
					},
					{
						value: 0,
						label: t('自定义'),
					},
				]
				if (!permission.has60FpsInH265) {
					supportedFps = supportedFps.filter(function (value) {
						return !/60fps/i.test(value.label)
					})
				}
			} else {
				supportedFps = [
					{
						value: 5,
						label: t('全高清（4M 1080P@60fps）'),
					},
					{
						value: 4,
						label: t('全高清（2M 1080P@30fps）'),
					},
					{
						value: 3,
						label: t('高清（2M 720P@30fps）'),
					},
					{
						value: 2,
						label: t('标清（256K W4CIF@25fps）'),
					},
					{
						value: 1,
						label: t('流畅（192K WCIF@25fps）'),
					},
					{
						value: 0,
						label: t('自定义'),
					},
				]
			}
		}
		if (!permission['60fps']) {
			supportedFps = supportedFps.filter(function (value) {
				return !/60fps/i.test(value.label)
			})
		}
		if (!permission['4K']) {
			supportedFps = supportedFps.filter(function (value) {
				return !/4K/i.test(value.label)
			})
		}
		if (!permission.enableHDMeeting) {
			supportedFps = supportedFps.filter(function (value) {
				return !(/1080P/i.test(value.label) || /4K/i.test(value.label))
			})
		}
		//只有纯转发会议才能有4K@60fps
		if (data.meetingType !== 0) {
			supportedFps = supportedFps.filter(function (value) {
				return !/4K@60fps/i.test(value.label)
			})
		}
		return supportedFps
	}, [data._H265, data.meetingType, permission])

	const { run: updateList } = useDebounceFn(
		//防抖
		() => {
			setSelfMediaAbilityList(Number(value))
			setSelfMediaAbilityVal(Number(useVirtualRoomStore.getState().data._selfMediaList[0].value))
		},
		{
			wait: 300,
		}
	)

	useEffect(() => {
		if (data._bitrateType === 0) {
			//初始化自定义下拉列表
			setSelfMediaAbilityList(data.rate)
		}
	}, [])

	useEffect(() => {
		setValue(data.rate ? String(data.rate) : '')
	}, [data.rate])

	return (
		<div className="line-wrap media-ability-line">
			<div className="label">{t('媒体能力')}</div>
			{data.meetingType !== 2 && (
				<div>
					<div className="h265-check">
						{!data.enableRtc && permission.h265 && (
							<>
								<CheckBox
									width={100}
									checked={data._H265}
									onChange={(e, v) => {
										changeH265(v)
										resetMeetingProtocol()
									}}
								>
									H.265
								</CheckBox>
								<CheckBox checked={true} disabled={true}></CheckBox>
							</>
						)}
						H.264{t('及其它')}
					</div>
					<div className="media-select">
						<Select
							container={() => containerRef.current}
							width={200}
							options={mediaAbilityList}
							value={data._bitrateType}
							onChange={(e, v) => {
								setMediaAbilityVal(v)
								if (v === 0) {
									//自定义媒体能力
									setSelfMediaAbilityList(undefined)
									setSelfMediaAbilityVal(0)
									setTimeout(() => {
										inputRef.current?.focus()
									})
								}
							}}
						/>
						{data._bitrateType === 0 && (
							<>
								<InputNumber
									ref={inputRef}
									className="self-input"
									width={80}
									placeholder={t('请输入码率')}
									focusMsg={t('自定义码率范围为64K~8M')}
									rule={getRule('rate')}
									value={value}
									onChange={(e, v) => {
										setValue(v)
										updateList()
									}}
									onBlur={(e, v) => {
										if (!v) {
											updateData({
												rate: undefined,
											})
											setSelfMediaAbilityList(undefined)
											return
										}
										let val = parseInt(v)
										let newVal = val
										if (!(val < 64 || val > 8192)) {
											newVal = val % 64 !== 0 ? val + 64 - (val % 64) : val
										}
										setValue(String(newVal))
										setSelfMediaAbilityList(newVal)
										setSelfMediaAbilityVal(
											Number(useVirtualRoomStore.getState().data._selfMediaList[0].value)
										)
										updateData({
											rate: newVal,
										})
										setValue(String(newVal))
									}}
								/>
								<span>Kbps</span>
								<Select
									container={() => containerRef.current}
									className="self-select"
									width={130}
									options={data._selfMediaList}
									value={data._selfMediaValue}
									onChange={(e, v) => setSelfMediaAbilityVal(v)}
								/>
							</>
						)}
					</div>
				</div>
			)}
			{data.meetingType === 2 && (
				<div className="sfu-media">
					<span>H.264</span>
					<Select
						width={180}
						container={() => containerRef.current}
						value={data._bitrateType}
						options={
							permission.enableHDMeeting
								? [
										{
											label: t('全高清(4M 1080p@30fps)'),
											value: 6,
										},
										{
											label: t('高清(2M 720p@30fps)'),
											value: 4,
										},
								  ]
								: [
										{
											label: t('高清(2M 720p@30fps)'),
											value: 4,
										},
								  ]
						}
						onChange={(e, v) => setSfuMediaValue(v)}
					/>
				</div>
			)}
		</div>
	)
}
